package operation;


import JDBC.JDBCUtils;
import Medicine.Pharmacy;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;


public class DelMedicine implements IOPeration {
    @Override
    public void work(Pharmacy pharmacy) throws SQLException {
        //创建QueryRunner对象
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource() );
        System.out.println(" 删除药品.... ");
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入您想要删除的药品");
        String name = sc.nextLine();

        String query = "SELECT Name FROM Medicine";
        int flag = 0;
        List<Map<String, Object>> medicineList = qr.query(query, new MapListHandler());
        for (Map<String, Object> medicineMap : medicineList) {
            if (medicineMap.get("name").equals(name)) {
                System.out.println("有你需要删除的药品");
                flag = 1;
                break;
            }
        }
        if(flag == 0){
            System.out.println("没有您想删除的药品");
            return;
        }

        //定义根据名字删除药材的SQL
        String sql = "DELETE FROM Medicine WHERE name=?";
        int count = qr.update(sql,name);
        //输出删除结果
        if(count < 1){
            System.out.println("删除药品失败！");
        }else{
            System.out.println("删除药品成功！");
        }

    }
}
